package com.sunfeng.n8;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 测试定时任务  实现每周四18:00:00执行定时任务
 *
 * @author sunfeng
 * @date 2021/04/21 08:46
 **/
@Slf4j(topic = "c.TestScheduled")
public class TestScheduled {
    public static void main(String[] args) {
        // 获取当前时间
        LocalDateTime now = LocalDateTime.now();

        log.debug("现在的时间为:{}",now);
        // 获取周四的时间
        LocalDateTime time = now.withHour(18).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.THURSDAY);
        // 如果当前时间大于周四  比如今天周五  需要在下周四开始执行任务
        if (now.compareTo(time) > 0) {
            time = time.plusWeeks(1);
        }
        log.debug("任务执行的时间为:{}",time);
        // 代表当前时间和周四的时间差
        long initialDelay = Duration.between(now, time).toMinutes();

        long period = 1000 * 60 * 60 * 24 * 7;

        ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(1);

        threadPool.scheduleAtFixedRate(() -> {
            log.debug("我开始执行任务了");
        }, initialDelay, period, TimeUnit.SECONDS);
    }
}
